$(document).ready(function(){
	typeof(THEME)=='undefined' && (THEME='blue/');
	
	initGraphWork();
});

/**
 * 初始化
 * */
function init(){
	    
	// 顶部下拉菜单
    var _li=$(".MenuList ul li");
    _li.mouseenter(function(){
        $(this).find("span").show();
    }).mouseleave(function(){
            $(this).find("span").hide();
    });
	
	  //选项卡封装
	   function tab(o1,o2,c,e){
	        o1.each(function(i){
	            $(this).bind(e,function(){
	                o2.hide().eq(i).fadeIn();
	                o1.removeClass(c);
	                $(this).addClass(c);
	            });
	            if ($(this).hasClass(c)) {
	                $(this).addClass(c);
	                o2.hide().eq(i).fadeIn();
	            }
	        });
	    }
	    //选项卡封装 end Bｙ:Qingya
	    tab($(".TabTop span"),$(".Tabconter ul"),"hover","click"); //选项卡封装调用

	    //工具效果
	    $(".Tool").toggle(function () {
		        $(".Tool").animate({
		            left:-1
		        });
	        },function () {
		        $(".Tool").stop().animate({
		            left:-47
		        });
	    });
	    //工具效果 end

	    $('.side-act').click(function(){
	    	var t = $(this);
	    	var on = t.attr('is-open')==null?true:false;
	    	
	    	if(on){
	    		$('.MainLeft').hide(100);
	    		t.attr('is-open',1);
	    		t.attr('class','side-act enlarge');
	    		$('.MainRight').css('margin-left','20px');
	    	}
	    	else{
	    		$('.MainLeft').show(50);
	    		t.removeAttr('is-open');
	    		$('.MainRight').css('margin-left','240px');
	    		t.attr('class','side-act narrow');
	    	}
	    });
}



/**
 * 加载模块化菜单
 * */
function loadModulesMenu(){
	$.ajax({
		type:"post",
		url : contextPath + "moduleMenu/getModulesMenus",
		dataType : "json",
		success : function(env){
			if(env.result){
				var datas = env.data;
				var departMentMenu = $(".MainLeft ul");
				var html ="";
				//var appDepartmentSelOpt ="";
				for(var index = 0; index < datas.length; index++){
					var departMent = datas[index];
					
					//appDepartmentSelOpt += "<option value=\""+departMent['id']+"\">"+departMent['name']+"</option>";
					var func = departMent.bindFunction;
					func = isEmpty(func) ? "" : "onclick='"+func+"()'" ;
					
					html +="<li " +func +">"+
							"<img src=\""+contextPath+departMent['imgPath'].replace(/resources\/images\//,'resources/'+THEME+'images/')+"\"><h1>"+departMent['name'] +"</h1>";
						if(!isEmpty(departMent['menus']) && departMent['menus'].length >0){
							html +="<span>" ;
							for(var j = 0; j < departMent['menus'].length; j++ ){
								html += "<a href=\"javascript:;\" onclick=\"openChooseFlowPage('"+departMent['menus'][j]['id']+"','"+
								departMent['menus'][j]['name']+"',this)\" >"+departMent['menus'][j]['name']+"</a>";
							}
							html +="</span>"; 
						}
					html += "</li>";
				}
				//$("#appDepartmentSel").append(appDepartmentSelOpt);
				departMentMenu.html(html);
			}else{
				MessageAlert(env.msg);
			}
		}
	});
}


function loadCurrentFlow(){
	if(!isEmpty(flowCfgId)){
		loadFlowCfg(flowCfgId,taskId);
	}
}



/**
 * 加载并监听工具栏
 * 组件
 * */
function loadToolMenu(){
	$.ajax({
		type:"post",
		url:contextPath+"toolMenu/getToolMenus",
		dataType:"json",
		success : function(env){
			if(env.result){
				var group = document.getElementById("groupTools");
				var datas = env.data;
				
				for(var index =0 ; index < datas.length ; index++ ){
					var spanDescLabel = document.createElement("span");
					if(index == 0)
						spanDescLabel.className ="hover";
					
					spanDescLabel.innerHTML=datas[index]['name'];
					group.appendChild(spanDescLabel);
					//group.append("<span>"+datas[index]['name']+"</span>");
					
					var modules = document.getElementById("opts");
					//var modules = $("#opts")
					
					var moduleUL = document.createElement("ul");
					//var html ="<ul>";
					var style = initStyle();
					for(var j=0 ; j< datas[index]['menus'].length; j++){
						var module = datas[index]['menus'][j];
						
						var moduleLI = document.createElement("li");
						var linkA = document.createElement("a");
						var imgDesc = document.createElement("img");
						imgDesc.src = contextPath+module['imgPath'];
						
						style = mxUtils.clone(style);
						//每个组件的图片路径
						style[mxConstants.STYLE_IMAGE] = contextPath+module['imgPath'];
						graph.getStylesheet().putCellStyle(module['name'], style);
						
						addVertex(imgDesc,70,70,module['name'],false,module['otherData']['funmodId'],module['otherData']['bondFunction']);
						var descH1 =document.createElement("h1");
						descH1.innerHTML =module['name'];
						
						linkA.appendChild(imgDesc);
						linkA.appendChild(descH1);
						moduleLI.appendChild(linkA);
						moduleUL.appendChild(moduleLI);
						
					}
					modules.appendChild(moduleUL);
				}
				
				init();
				loadCurrentFlow();
			}else{
				MessageAlert(env.msg);
			}
		}
	});
}

/**
 * 打开历史运行任务
 * */
function openMyRunTask(){
	//if(auth("open","您没有打开的权限!")){
		 $.get(contextPath+'pages/flow/chooseTask.jsp', function(data) {
			  var d = new Boxy(data,{
				  title : "我的挖掘",
				  unloadOnHide : true,
				  draggable : true,
				  center : true,
				  modal : true
			  });
			 
			  GLOB.dlg.chooseTaskDlg = d;
			  
			  createTaskGrid();
		  });
	//}
}


/**
 * 监听Label的改变事件
 * */
function listenerLabelChange(){
	graph.addListener(mxEvent.LABEL_CHANGED, function(sender, evt){
		var cell = evt.getProperty("cell");
		var label = cell.getValue();
		var stepId = cell.getStepId();
		$.post(contextPath+"stepCfgController/stepCfg/updateStepCfgLabel",{
			label : label,
			stepId : stepId
		},function(env){
			if(!env.result){
				MessageAlert(env.msg);
			}
		},"json");
	});
}


function initGraphWork(){
	if(!mxClient.isBrowserSupported()){
		mxUtils.error('Browser is not support!',200, false);
	}else{
		initImgConn(contextpath+'resources/images/connector.gif');
		createGraphArea("graphWorkSpace");
		graphListennerHandler();
		//loadModulesMenu();
		//loadToolMenu();
		listenerGraphCell();
		listenerLabelChange();
		initOutLine("miniature");
		//loadSelDepartMentTree();	//加载部门树
	}
}



/**
 * 通过流程ID,加载流程配置
 * */
function loadFlowCfg(flowId,loadTaskId){
	
	//停止正在运行流程
	$.each(GLOB.run,function(k,val){
		stopScanServer(val.getTaskId());
	});
	
	
	$.each(GLOB.server.scanServer,function(k,val){
		stopScanServer(k);
	});
	
	$.ajax({
		type: "post",
		url :contextPath+"flowController/flowCfg/loadFlowCfg",
		data : "flowId="+flowId,
		dataType : "json",
		success : function(env){
			if(env.result){
				//停止当前栏目运行按钮图标
				$('#oper-task').addClass("start").removeClass("stop");
				$('#oper-task').text() != null && ($('#oper-task').text('启动').attr('title','启动'));
				
				flowCfgId = env.data.flowId;
				taskId = loadTaskId;
				//加载历史画布
				if(!isEmpty(env.data.xmlInfo)){
					var doc = mxUtils.parseXml(env.data.xmlInfo);
					var codec = new mxCodec(doc);
					codec.decode(doc.documentElement, graph.getModel());
				}
				var d = GLOB.dlg.chooseFLowDlg;
				if(!isEmpty(d)) d.hide();
				
				if(!isEmpty(loadTaskId)){
					scanServer(loadTaskId);
				}
				else
					stopScanServer(loadTaskId);
				
				if(!GLOB.title)
					GLOB.title = document.title;
				
				//标题
				document.title = env.data.flowName+'_'+GLOB.title;
				
				var nav_str = "";
				
				if(env.nav.f_app_name)
					nav_str += env.nav.f_app_name+" &gt; ";
				
				if(env.nav.app_name)
					nav_str += env.nav.app_name+" &gt; ";
				
				if(env.nav.flow_name)
					nav_str += env.nav.flow_name;
				
				$('#task-nav').html(nav_str);
			}else{
				MessageAlert(env.msg);
			}
		}
	});
}


function move(){
	var default_unit = 100;
	var view = graph.getView();
	var scale = view.getScale();
	var translate = view.getTranslate();
	var x = translate.x;
	var y = translate.y;
	
	view.setTranslate(x + default_unit * scale, y + default_unit*scale);
}

/**
 * 重置配置
 * @param stepId
 */
function columnList_reset(stepId){
	if(confirm('确认要重置当前上下文参数吗？')){
		var url = contextPath+'typeParam/resetColumnAttr';
		$.post(url,{
			stepId:stepId,
			reset:1
		},function(env){
			if(env.result){
				MessageAlert(env.msg);
			}else{
				MessageAlert(env.msg);	
			}
		});
	}
}


//========================================左边模块功能加载页面实现 start===================================================
/**
 * 按部门分类、按功能分类、我的挖掘、系统管理
 * @param appId 部门ID
 * @param 部门名称
 * */
function openChooseFlowPage(appId,departMentName,dthis){
	$('.MainLeft span a').removeClass('active');
	$(dthis).addClass('active');
	//if(auth("open","您没有打开的权限!")){
	  Boxy.DEFAULTS.title = "分类";
	  
	  $.ajax({
		  type : "post",
		  url : contextPath + "flowController/flowCfg/getFlowByAppId",
		  data : "appId="+appId,
		  dataType : "json",
		  success: function(evn){
			  if(evn.result){
				  var flows = evn.data;
				  var htmlStr ="<ul>";
				  for(var i=0; i< flows.length; i++){
					  htmlStr +="<li><a href=\"#"+flows[i]['flowId']+"\" onclick=\"loadFlowCfg('"+flows[i]['flowId']+"')\">"+flows[i]['flowName']+"</a></li>";
				  }
				  htmlStr += "</ul>";
				  $.get(contextPath+'pages/flow/chooseFlow.jsp', function(data) {
					  var d = new Boxy(data,{
						  title : "选择流程",
						  unloadOnHide : true,
						  modal : true
					  });
					  $(".Settoptxt h3").html(departMentName);
					  $('#flowContent').html(htmlStr);
					  GLOB.dlg.chooseFLowDlg = d;
				  });
			  }else{
				  MessageAlert(evn.msg);
			  }
		  }
	  });
	//}
	  
}


//========================================左边模块功能加载页面实现 end===================================================

//========================================= 画布中工具栏功能实现 start==========================================
/**
 * 打开新建画布编辑窗口
 * */
function createNewGraph(){
	//if(auth("create","您没有创建流程的权限!")){
		$.get(contextPath+'pages/flow/creatFlow.jsp',{
			
		} ,function(data) {
			  var d = new Boxy(data,{
				  title : "创建流程",
				  unloadOnHide : true,
				  draggable : true,
				  modal : true
			  });
			  GLOB.dlg.createFlowDlg = d;
			  
			  loadSelDepartMentTree();
		 });
	//}
}


/**
 * 打开  操作
 * */
function openFlowMenu(){
	//if(auth("open","您没有打开的权限!")){
		$.get(contextPath+'pages/flow/openFlowMenu.jsp',{
			
		} ,function(data) {
			  var d = new Boxy(data,{
				  title : "打开",
				  unloadOnHide : true,
				  draggable : true,
				  modal : true
			  });
			  GLOB.dlg.openFlowMenuDlg = d;
			  
			  init();
		 });
	//}
}



/**
 * 保存XML文件
 * */
function saveFlowXMLGraph(func){
	//if(auth("save","您没有保存流程的权限!")){
		var xml = getGraphXML();
		
		$.post(contextPath+"flowController/flowCfg/saveFlowXML",{
			xml : xml,
			flowCfgId : flowCfgId
		},function(env){
			if(env.result){
				MessageSlide(env.msg);
				func && func();
			}
			else
				MessageAlert(env.msg);
		},"json");
	//}
}



/**
 * 启动流程
 * @param runType
 * @param endStepId
 */
function startFlowRunner(runType,endStepId){
	if(!auth("run","您没有启动流程的权限!")){
		return false;
	}
	var data ="cmd=start&flow_id="+flowCfgId+"&user_id="+userId+"&run_type="+runType+(isEmpty(endStepId)? "": "&end_step_id="+endStepId);
	//清空状态
	clearState();
	
	//saveFlowXMLGraph(function(){
		//运行
		$.ajax({
			type : "post",
			data: data,
			url : contextPath + "flowController/flowCfg/startOrEndFlow",
			dataType : "json",
			success : function(env){
				if(env.result && env.status.indexOf("0") != -1){
					taskId= env.taskId;
					$('#oper-task').addClass("stop").removeClass("start");
					$('#oper-task').text() != null && ($('#oper-task').text('停止').attr('title','停止'));
					
					starScanServer(env.taskId);
					MessageSlide("启动流程成功!");
				}else{
					MessageAlert(env.msg);
				}
			}
		});
	//});
}

/**
 * 停止流程
 * @param runType
 * @param endStepId
 */
function stopFlowRunner(runType,endStepId,ItaskId){
	if(!auth("run","您没有停止的流程的权限!")){
		return false;
	}
	ItaskId = ItaskId || taskId;
	var cmd ="stop";
	//停止所有子流程
	var size = 0;
	
	$.each(GLOB.server.scanServer,function(k,val){
		size++;
	});
	
	if(endStepId==-1 && size>1){
		$.each(GLOB.server.scanServer,function(k,val){
			stopFlowRunner(runType,-2,k);
		});
		return;
	}
	
	stopScanServer(ItaskId);
	$.ajax({
		type : "post",
		data: "cmd="+cmd+"&flow_id="+flowCfgId+"&task_id="+ItaskId,
		url : contextPath + "flowController/flowCfg/startOrEndFlow",
		dataType : "json",
		success : function(env){
			//移除滚动条
			removeLoading(ItaskId);
			if(env.result && env.status.indexOf("0") != -1){
				MessageSlide("停止流程成功!");
			}else{
				MessageAlert(env.status);
			}
		}
	});
}


/**
 * 流程控制
 * 0
 * */
function startOrStopFlowRunner(runType,endStepId){
	if(auth("run","您没有启动或停止的流程的权限!")){
		if(!isEmpty(flowCfgId)){
			if($('#oper-task').hasClass("start")){
				startFlowRunner(runType,endStepId);
			}else{
				stopFlowRunner(runType,endStepId);
			}
		}else{
			MessageAlert("该流程没有流程编号,不能运行!");
		}
	}
}


function scanServer(taskId){
	if(!isEmpty(taskId)){
		$.ajax({
			type : "post",
			data: "cmd=state&flow_id="+flowCfgId+"&task_id=" +taskId,
			url : contextPath + "flowController/flowCfg/startOrEndFlow",
			dataType : "json",
			success :function(env){
				if(!isEmpty(env)){
					//状态
					setState(env.step,taskId);
					
					//从子流程里面打印错误信息
					PrintStepMessage(env.step,taskId);
					
					if(/complete|cancel|failed/.test(env.task_state)){
						stopScanServer(taskId);
					}else{
						if(env.result){
							if(env.status.indexOf("complete") != -1 || env.status.indexOf("cancel") != -1 || env.status.indexOf("-1") != -1 ){
								var step_id = env.step[env.step.length-1].step_id;
								GLOB.run[step_id] && GLOB.run[step_id].setState(0);
								stopScanServer(taskId);
							}else{
								GLOB.server.scanServer[taskId] = setTimeout(function(){
									scanServer(taskId);
								},3*1000);
								$('#oper-task').addClass("stop").removeClass("start");
								$('#oper-task').text() != null && ($('#oper-task').text('停止').attr('title','停止'));
							}
						}else{
							if(!env.step){
								GLOB.server.scanServer[taskId] = setTimeout(function(){
									scanServer(taskId);
								},3*1000);
							}else{
								MessageAlert(env.msg);
							}
						}
					}
				}else{
					stopScanServer(taskId);
				}
			}
		});
	}
}

function clearState(){
	if(!isEmpty(graph)){
		var cells = getAllCells();
		for(var i = 0 ; i< cells.length; i++){
			var cell = cells[i];
			var cellOverlays = graph.getCellOverlays(cell);
			if(cellOverlays != null) graph.removeCellOverlays(cell);
		}
	}
}

/**
 * 读取所以节点
 * @returns
 */
function getAllCells(){
	var bossCell = graph.getDefaultParent();
	var cells = graph.getChildVertices(bossCell);
	return cells;
}

/**
 * 移除滚动条
 */
function removeLoading(taskId){
	var cells = getAllCells();
	for(var i = 0; i< cells.length; i++){
		var cell = cells[i];
		var cellOverlays = graph.getCellOverlays(cell);
		if(cellOverlays){
			for(var j=0;j<cellOverlays.length;j++){
				if(taskId == cell.getTaskId() && /running\.gif$/.test(cellOverlays[j].image.src)){
					graph.removeCellOverlays(cell);
					var overlay = new mxCellOverlay(new mxImage(contextPath +"resources/images/status/stop.gif",16,16),
							"停止",mxConstants.ALIGN_RIGHT,mxConstants.ALIGN_BOTTOM,new mxPoint(-10,-20),
							"hand");
					graph.addCellOverlay(cell,overlay);
				}
			}
		}
	}
}

/**
 * 结束流程，设置每个节点的状态
 * @param taskId
 * @param state
 */
function setOverTask(taskId,state){
	var cells = getAllCells();
	for(var i = 0; i< cells.length; i++){
		var cell = cells[i];
		if(taskId == cell.getTaskId()){
			cell.setState(0);
		}
	}
};

/**
 * 设置状态
 * @param stepObj
 * @param taskId
 */
function setState(stepObj,taskId){
	if(!isEmpty(graph) && !isEmpty(stepObj)){
		var cells = getAllCells();
		
		for(var i = 0; i< stepObj.length; i++){
			var statusObj = stepObj[i];
			var cell = findInGroupMxCellByStepId(cells, statusObj.step_id);
			cell && cell.setTaskId(taskId);
			var stepState = statusObj.step_state;
			
			if(!isEmpty(cell) && "ready" != stepState){
				var cellOverlays = graph.getCellOverlays(cell);
				if(cellOverlays != null) graph.removeCellOverlays(cell);
				var overlay = new mxCellOverlay(new mxImage(contextPath +"resources/images/status/"+stepState+".gif",16,16),
						"提示消息",mxConstants.ALIGN_RIGHT,mxConstants.ALIGN_BOTTOM,new mxPoint(-10,-20),
						"hand");
				graph.addCellOverlay(cell,overlay);
			}
		}
	}
}

/**
 * 打印流程错误消息
 * @param stepObj
 * @param taskId
 */
function PrintStepMessage(stepObj,taskId){
	if(!isEmpty(graph) && !isEmpty(stepObj)){
		var cells = getAllCells();
		
		for(var i = 0; i< stepObj.length; i++){
			var statusObj = stepObj[i];
			var cell = findInGroupMxCellByStepId(cells, statusObj.step_id);
			var stepState = statusObj.step_state;
			
			if(!isEmpty(cell) && /failed|cancel/.test(stepState)){				
				if(!GLOB.server.showed[statusObj.step_id]){
					GLOB.server.showed[statusObj.step_id] = 1;
					MessageAlert(!isEmpty(statusObj.msg)?statusObj.msg:'未知错误');
				}
			}
		}
	}
}

/**
 * 从数组中找到stepId的mxCell
 * @param cells
 * @param stepId
 * @returns
 */
function findInGroupMxCellByStepId(cells , stepId ){
	for(var i =0 ; i < cells.length; i++){
		var cell = cells[i];
		if(cell.getStepId() == stepId){
			return cell;
		}
	}
}


/**
 * 开始扫描服务
 */
function starScanServer(taskId){
	scanServer(taskId);
}
/**
 * 停止扫描服务
 */
function stopScanServer(taskId){
	GLOB.server.showed = {};
	setOverTask(taskId,0);
	if(!isEmpty(GLOB.server.scanServer[taskId])){
		clearTimeout(GLOB.server.scanServer[taskId]);
		GLOB.server.scanServer[taskId] = null;
		
		$.each(GLOB.run,function(k,val){
			if(val.getTaskId()==taskId){
				GLOB.run[k] = null;
				delete GLOB.run[k];
			};
		});
		
		var size = 0;
		$.each(GLOB.run,function(k,val){
			size++;
		});
		
		if(size<1){
			$('#oper-task').addClass("start").removeClass("stop");
			$('#oper-task').text() != null && ($('#oper-task').text('启动').attr('title','启动'));
		}
	}
}





/**
 * 当前方法后期需要修改,暂时默认新建至部门分类的财务部中
 * */
function createGraph(){
	$.post(contextPath+"flowController/flowCfg/systemCreateGraphDefaultName",{
		
	},function(env){
		if(env.result){
			flowCfgId = env.flowCfgId;
			taskId = null;
			removeAllCell();
			MessageSlide(env.msg);
			//removeAllCell();
			//flowCfgClose();
		}else{
			alert(env.msg);
		}
	},"json");
}

//========================================= 画布中工具栏功能实现 end==========================================


function auth(auth,errMsg){
	if(!GLOB.auths.contains(auth)){
		MessageSlide(errMsg);
		return false;
	}
	return true;
}

function closeWebPage() {  
    if (navigator.userAgent.indexOf("MSIE") > 0) {  
        if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {  
            window.opener = null; window.close();  
        }  
        else {  
            window.open('', '_top'); window.top.close();  
        }  
    }  
    else if (navigator.userAgent.indexOf("Firefox") > 0) {  
        window.location.href = 'about:blank ';  
        //window.history.go(-2);  
    }  
    else {  
        window.opener = null;   
        window.open('', '_self', '');  
        window.close();  
    }  
}  
